import 'dart:async';
import 'ms_websocket_trans_service.dart';
import '../app_logger.dart';

/// WebSocket连接管理器（单例）
/// 负责管理全局的WebSocket连接，避免应用切换时断开连接
class WebSocketConnectionManager {
  static WebSocketConnectionManager? _instance;
  static WebSocketConnectionManager get instance => _instance ??= WebSocketConnectionManager._();
  
  WebSocketConnectionManager._();
  
  MSWebSocketTransService? _service;
  int _referenceCount = 0; // 引用计数
  Timer? _disconnectTimer; // 延迟断开定时器
  
  /// 获取WebSocket服务实例
  MSWebSocketTransService getService() {
    if (_service == null) {
      _service = MSWebSocketTransService();
      log.d('🔌 创建新的WebSocket服务实例');
    }
    
    _referenceCount++;
    log.d('📊 WebSocket服务引用计数: $_referenceCount');
    
    // 取消延迟断开定时器
    _disconnectTimer?.cancel();
    _disconnectTimer = null;
    
    return _service!;
  }
  
  /// 释放WebSocket服务引用
  void releaseService() {
    _referenceCount--;
    log.d('📊 WebSocket服务引用计数: $_referenceCount');
    
    // 当没有任何地方引用时，延迟断开连接
    if (_referenceCount <= 0) {
      _referenceCount = 0;
      
      // 取消之前的定时器
      _disconnectTimer?.cancel();
      
      // 延迟5分钟后断开连接，给用户重新进入应用的时间
      _disconnectTimer = Timer(const Duration(minutes: 5), () {
        if (_referenceCount == 0 && _service != null) {
          log.d('🔌 无引用且超时，断开WebSocket连接');
          _service!.dispose();
          _service = null;
        }
        _disconnectTimer = null;
      });
      
      log.d('⏰ 启动5分钟延迟断开定时器');
    }
  }
  
  /// 强制断开连接（应用完全关闭时调用）
  void forceDisconnect() {
    _disconnectTimer?.cancel();
    _disconnectTimer = null;
    
    if (_service != null) {
      log.d('🔌 强制断开WebSocket连接');
      _service!.dispose();
      _service = null;
    }
    _referenceCount = 0;
  }
  
  /// 检查连接状态
  bool get isConnected => _service?.isConnected ?? false;
  
  /// 获取当前服务器名称
  String get currentServerName => _service?.getServerName() ?? '';
  
  /// 手动重连（供UI调用）
  Future<void> reconnect() async {
    if (_service != null && !_service!.isConnected) {
      try {
        await _service!.connect();
        log.d('🔄 手动重连WebSocket成功');
      } catch (e) {
        log.d('❌ 手动重连WebSocket失败: $e');
        rethrow;
      }
    }
  }
}